<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="赛事名称" prop="competitionName">
        <el-input v-model="queryParams.competitionName" placeholder="请输入赛事名称" clearable style="width: 200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="团队名称" prop="teamName">
        <el-input v-model="queryParams.teamName" placeholder="请输入团队名称" clearable style="width: 200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="获奖等级" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择获奖等级" clearable style="width: 120px">
          <el-option v-for="level in awardLevelOptions" :key="level" :label="level" :value="level" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['commgr:award:add']">上报获奖</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['commgr:award:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['commgr:award:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['commgr:award:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-info" size="mini" @click="handleDebug">调试</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="awardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="获奖编号" align="center" prop="awardId" width="80" />
      <el-table-column label="赛事名称" align="center" prop="competitionName" min-width="150" />
      <el-table-column label="赛项名称" align="center" prop="comItemName" min-width="120" />
      <el-table-column label="团队名称" align="center" prop="teamName" min-width="120" />
      <el-table-column label="届次数" align="center" prop="sessionNum" width="80" />
      <el-table-column label="获奖等级" align="center" prop="level" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.level }}</span>
        </template>
      </el-table-column>
      <el-table-column label="获奖证书" align="center" width="100">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.certificate" :src="scope.row.certificate" :width="50" :height="50" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['commgr:award:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['commgr:award:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改获奖记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 新增时显示团队选择 -->
        <template v-if="!form.awardId">
          <el-form-item label="参赛团队" prop="teamId">
            <el-select v-model="form.teamId" placeholder="请选择团队" @change="handleTeamChange" style="width: 100%"
              :loading="teamLoading">
              <el-option v-for="team in teamList" :key="team.teamId" :label="getTeamDisplayLabel(team)"
                :value="team.teamId" />
            </el-select>
            <div v-if="form.teamId && !hasPermission" style="color: #f56c6c; font-size: 12px; margin-top: 5px;">
              无权限上报该团队或团队未通过审核
            </div>
            <div v-if="teamList.length === 0" style="color: #e6a23c; font-size: 12px; margin-top: 5px;">
              暂无可用团队，请先加入团队并确保团队已通过审核
            </div>
          </el-form-item>

          <el-form-item label="赛事名称">
            <el-input v-model="form.competitionName" readonly />
          </el-form-item>

          <el-form-item label="赛项名称">
            <el-input v-model="form.comItemName" readonly />
          </el-form-item>
        </template>

        <!-- 修改时显示完整信息 -->
        <template v-else>
          <el-form-item label="赛事名称">
            <el-input v-model="form.competitionName" readonly />
          </el-form-item>

          <el-form-item label="赛项名称">
            <el-input v-model="form.comItemName" readonly />
          </el-form-item>

          <el-form-item label="团队名称">
            <el-input v-model="form.teamName" readonly />
          </el-form-item>

          <el-form-item label="届次数">
            <el-input v-model="form.sessionNum" readonly />
          </el-form-item>

          <el-form-item label="比赛届次ID" prop="sessionId">
            <el-input v-model="form.sessionId" placeholder="请输入比赛届次ID" />
          </el-form-item>

          <el-form-item label="团队ID" prop="teamId">
            <el-input v-model="form.teamId" placeholder="请输入团队ID" />
          </el-form-item>
        </template>

        <el-form-item label="获奖等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择获奖等级" style="width: 100%">
            <el-option v-for="level in awardLevelOptions" :key="level" :label="level" :value="level" />
          </el-select>
        </el-form-item>

        <el-form-item label="获奖证书" prop="certificate">
          <el-upload ref="upload" action="#" :auto-upload="false" :on-change="handleFileChange"
            :on-remove="handleFileRemove" :file-list="fileList" :before-upload="beforeUpload" accept=".png,.jpg,.jpeg"
            list-type="picture" :limit="1">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传png/jpg/jpeg文件，且不超过5MB
              <div v-if="form.certificate" style="color: #67c23a; margin-top: 5px;">
                当前已有证书: {{ form.certificate }}
              </div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listAward,
  getAward,
  delAward,
  addAward,
  updateAward,
  reportAward,
  getMyTeams,
  getCompetitionInfo,
  checkPermission,
  exportAward,
  updateAwardWithFile,
} from "@/api/commgr/award";

export default {
  name: "Award",
  data() {
    return {
      // 获奖等级选项（直接使用文本）
      awardLevelOptions: ['特等奖', '一等奖', '二等奖', '三等奖', '优胜奖'],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 获奖记录表格数据
      awardList: [],
      // 团队列表数据
      teamList: [],
      // 团队加载状态
      teamLoading: false,
      // 是否有权限
      hasPermission: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        competitionName: null,
        teamName: null,
        level: null,
      },
      // 表单参数
      form: {},
      // 文件列表
      fileList: [],
      // 表单校验
      rules: {
        teamId: [
          { required: true, message: "参赛团队不能为空", trigger: "change" }
        ],
        level: [
          { required: true, message: "获奖等级不能为空", trigger: "change" }
        ]
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 获取团队显示标签 */
    getTeamDisplayLabel(team) {
      const parts = [team.teamName];
      if (team.competitionName) parts.push(team.competitionName);
      if (team.comItemName) parts.push(team.comItemName);
      if (team.approvalStatus === 'pending') parts.push('(待审核)');

      return parts.join(' - ');
    },

    /** 查询获奖记录列表 */
    getList() {
      this.loading = true;
      listAward(this.queryParams).then((response) => {
        this.awardList = response.rows;
        this.total = response.total;
        this.loading = false;

        console.log('获奖记录列表:', this.awardList);
      }).catch(error => {
        console.error('获取获奖记录列表失败:', error);
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        awardId: null,
        sessionId: null,
        teamId: null,
        level: null,
        certificate: null,
        competitionName: null,
        comItemName: null,
        teamName: null
      };
      this.fileList = [];
      this.hasPermission = true;

      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }

      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields();
      }
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.awardId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMyTeams();
      this.open = true;
      this.title = "上报获奖信息";
    },

    // 获取用户有权限的团队列表
    async getMyTeams() {
      this.teamLoading = true;
      try {
        const response = await getMyTeams();
        console.log('团队列表响应:', response);
        this.teamList = response.data || [];

        // 根据审核状态分类
        const approvedTeams = this.teamList.filter(team => team.approvalStatus === 'approved');
        const pendingTeams = this.teamList.filter(team => team.approvalStatus === 'pending');

        console.log('审核通过团队:', approvedTeams);
        console.log('待审核团队:', pendingTeams);

        if (this.teamList.length === 0) {
          // 如果没有团队，获取调试信息
          await this.getDebugInfo();
        } else if (approvedTeams.length === 0 && pendingTeams.length > 0) {
          this.$modal.msgWarning(`您有 ${pendingTeams.length} 个团队正在审核中，请等待审核通过后再上报获奖`);
        } else if (approvedTeams.length > 0) {
          // 只显示审核通过的团队
          this.teamList = approvedTeams;
          this.$modal.msgSuccess(`找到 ${approvedTeams.length} 个可上报的团队`);
        }

      } catch (error) {
        console.error('获取团队列表失败:', error);
        this.$modal.msgError("获取团队列表失败");
      } finally {
        this.teamLoading = false;
      }
    },

    // 获取调试信息
    async getDebugInfo() {
      try {
        const debugResponse = await this.$http.get('/commgr/award/checkAllTeams');
        console.log('调试团队信息:', debugResponse.data);

        const allTeams = debugResponse.data.allTeams || [];
        const validTeams = debugResponse.data.validTeams || [];

        if (allTeams.length === 0) {
          this.$modal.msgWarning("您还没有加入任何团队，请先加入团队");
        } else if (validTeams.length === 0) {
          this.$modal.msgWarning(`您有 ${allTeams.length} 个团队，但都没有通过实训中心审核，无法上报获奖`);
        }
      } catch (error) {
        console.error('获取调试信息失败:', error);
        this.$modal.msgWarning("未找到可上报的团队，请确认：\n1. 您有所属团队\n2. 团队已通过实训中心审核\n3. 团队类型为参赛团队或指导团队");
      }
    },

    // 团队选择变化
    async handleTeamChange(teamId) {
      if (teamId) {
        try {
          // 获取赛事信息
          const compResponse = await getCompetitionInfo(teamId);
          console.log('赛事信息响应:', compResponse);
          const data = compResponse.data;
          if (data) {
            this.form.competitionName = data.competitionName;
            this.form.comItemName = data.comItemName;
            this.form.sessionId = data.sessionId;
            this.form.teamName = data.teamName;
          } else {
            this.form.competitionName = null;
            this.form.comItemName = null;
            this.form.sessionId = null;
            this.form.teamName = null;
          }

          // 检查权限
          const permResponse = await checkPermission(teamId);
          console.log('权限检查响应:', permResponse);
          this.hasPermission = permResponse.data;

          if (!this.hasPermission) {
            this.$modal.msgError("无权限上报该团队获奖信息或团队未通过审核");
          }
        } catch (error) {
          console.error('获取团队信息失败:', error);
          this.$modal.msgError("获取团队信息失败");
          this.form.competitionName = null;
          this.form.comItemName = null;
          this.form.sessionId = null;
          this.form.teamName = null;
          this.hasPermission = false;
        }
      } else {
        this.form.competitionName = null;
        this.form.comItemName = null;
        this.form.sessionId = null;
        this.form.teamName = null;
        this.hasPermission = true;
      }
    },

    // 文件上传前校验
    beforeUpload(file) {
      const isImage = /\.(png|jpg|jpeg)$/i.test(file.name);
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$modal.msgError("上传文件只能是 PNG、JPG、JPEG 格式!");
        return false;
      }
      if (!isLt5M) {
        this.$modal.msgError("上传文件大小不能超过 5MB!");
        return false;
      }
      return true;
    },

    // 文件变化
    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(-1); // 只保留最后一个文件
    },

    // 文件移除
    handleFileRemove(file, fileList) {
      this.fileList = fileList;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const awardId = row.awardId || this.ids;
      getAward(awardId).then((response) => {
        this.form = response.data;

        // 确保文件列表也正确设置（如果有证书）
        if (this.form.certificate) {
          this.fileList = [{
            name: '获奖证书',
            url: this.form.certificate
          }];
        }

        this.open = true;
        this.title = "修改获奖记录";

        console.log('修改表单数据:', this.form);
      }).catch(error => {
        console.error('获取获奖记录详情失败:', error);
        this.$modal.msgError("获取详情失败");
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.awardId != null) {
            // 修改操作
            this.updateAward();
          } else {
            // 新增操作 - 使用文件上传方式
            if (this.fileList.length === 0) {
              this.$modal.msgError("请上传获奖证书");
              return;
            }

            if (!this.hasPermission) {
              this.$modal.msgError("无权限上报该团队获奖信息");
              return;
            }

            const formData = new FormData();
            formData.append("sessionId", this.form.sessionId);
            formData.append("teamId", this.form.teamId);
            formData.append("level", this.form.level);
            formData.append("certificateFile", this.fileList[0].raw);

            reportAward(formData).then(response => {
              this.$modal.msgSuccess("上报成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('上报失败:', error);
              this.$modal.msgError("上报失败: " + (error.message || '未知错误'));
            });
          }
        }
      });
    },

    /** 修改获奖记录 */
    updateAward() {
      // 如果有新文件上传
      if (this.fileList.length > 0 && this.fileList[0].raw) {
        const formData = new FormData();
        formData.append("awardId", this.form.awardId);
        formData.append("sessionId", this.form.sessionId);
        formData.append("teamId", this.form.teamId);
        formData.append("level", this.form.level);
        formData.append("certificateFile", this.fileList[0].raw);

        // 使用专门的修改接口
        updateAwardWithFile(formData).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        }).catch(error => {
          console.error('修改获奖记录失败:', error);
          this.$modal.msgError("修改失败: " + (error.message || '未知错误'));
        });
      } else {
        // 没有新文件，直接更新
        const updateData = {
          awardId: this.form.awardId,
          sessionId: this.form.sessionId,
          teamId: this.form.teamId,
          level: this.form.level,
          certificate: this.form.certificate
        };

        updateAward(updateData).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        }).catch(error => {
          console.error('修改获奖记录失败:', error);
          this.$modal.msgError("修改失败");
        });
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const awardIds = row.awardId || this.ids;
      this.$modal
        .confirm('是否确认删除获奖记录编号为"' + awardIds + '"的数据项？')
        .then(() => {
          return delAward(awardIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有获奖记录数据项？').then(() => {
        this.download('commgr/award/export', {
          ...queryParams
        }, `award_${new Date().getTime()}.xlsx`)
      }).catch(() => { });
    },

    /** 调试按钮操作 */
    handleDebug() {
      this.getMyTeams();
      this.$modal.msgSuccess("调试信息请查看控制台");
    },
  },
};
</script>

<style scoped>
.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.debug-modal {
  max-width: 80%;
}
</style>
